<template>
  <div class="home">
    <!--创建地图容器-->
    <div id="container" class="allmap"></div>
  </div>
</template>
   
  <script>
import { BMPGL } from "@/bmpgl.js";
export default {
  name: "Map",
  data() {
    return {
      ak: "", // 百度地图秘钥填写自己的ak
      myMap: null,
      latitude: null,
      longitude: null,
      address: "",
    };
  },
  created() {
    localStorage.getItem("latitude")
      ? (this.latitude = localStorage.getItem("latitude"))
      : (this.latitude = "");
    localStorage.getItem("longitude")
      ? (this.longitude = localStorage.getItem("longitude"))
      : (this.longitude = "");
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      // 传入密钥获取地图回调。
      BMPGL(this.ak)
        .then((BMapGL) => {
          // 创建地图实例
          let map = new BMapGL.Map("container");
          // 创建点坐标 axios => res 获取的初始化定位坐标
          let point = new BMapGL.Point(this.longitude, this.latitude);
          // 初始化地图，设置中心点坐标和地图级别
          map.centerAndZoom(point, 19);
          //开启鼠标滚轮缩放
          map.enableScrollWheelZoom(true);
          map.setHeading(64.5);
          map.setTilt(73);

          var geolocation = new BMapGL.Geolocation();
          geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              map.centerAndZoom(r.point, 15); //r.point就是当前定位坐标，设置为地图中心点
              var mk = new BMapGL.Marker(r.point);
              map.addOverlay(mk); //添加标点
              map.panTo(r.point);
              console.log("您的位置：" + r.point.lng + "," + r.point.lat);
              this.address = `${r.address.province} ${r.address.city} ${r.address.district} ${r.address.street} ${r.address.street_number}`; //中文 详细地址
              localStorage.setItem("address", this.address);
            } else {
              alert("failed" + this.getStatus());
            }
          });

          // 保存数据
          this.myMap = map;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
  <style  scoped>
.allmap {
  width: 100%;
  height: 100vh;
  position: relative;
  z-index: 1;
}
</style>
   